package com.syn.michat.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.syn.michat.constant.ErrorContants;
import com.syn.michat.pojo.User;
import com.syn.michat.util.exception.ClientException;

import java.util.Calendar;
import java.util.Date;

/**
 * token工具类
 **/

public class TokenUtil {

    //私钥设置
    private static final String TOKEN_SECRET = "5xcJVrXNyQDIxK1l2RS123";

    /**
    * @Description: 创建token
    * @Params: [userId, username] 用户ID，用户名
    * @return: java.lang.String
    * @Author: 申铭
    * @Date: 2021/12/16
    */
    public String getToken(String userId, String username) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date()); // 设置起时间
        cal.add(Calendar.YEAR, 1); // 增加一年

        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        String token = JWT.create()
                .withIssuer("michat")
                .withIssuedAt(new Date())
                .withExpiresAt(cal.getTime()) // 一年后过期
                .withClaim("username",username)
                .withClaim("userId",userId)
                .sign(algorithm);

        return token;
    }
    
    /**
    * @Description: 验证token
    * @Params: [token]
    * @return: void
    * @Author: 申铭
    * @Date: 2021/12/16
    */ 
    public User verifyToken(String token) throws ClientException {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer("michat")
                    .build();
            DecodedJWT jwt = verifier.verify(token);

            String username = jwt.getClaim("username").asString();
            String userId = jwt.getClaim("userId").asString();

            User user = new User();
            user.setUserId(userId);
            user.setUsername(username);
            return user;
        } catch (TokenExpiredException e) {
            throw new ClientException(ErrorContants.ACCESSTOKEN_INVALID, "token过期", null);
        } catch (JWTVerificationException e) {
            throw new ClientException(ErrorContants.ACCESSTOKEN_ILLEGAL, e.getMessage(), null);
        }
    }
}
